import OSS from "ali-oss";

const getFileNameUUID = fileName => {
	let name = "hopermall";
	// if (fileName) {
	//     name = fileName.substring(0, fileName.indexOf('.'))
	// }
	function rx() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}
	return `${name}_${+new Date()}_${rx()}${rx()}`;
};

const uploadFile = async function(obj, callback) {
	console.log(1111, obj);
	let client = new OSS({
		region: "oss-cn-beijing",
		accessKeyId: "LTAIglk3U0Ciq99U",
		accessKeySecret: "ex4zcQ1nDJ6bGwuVU21XYH0tedVnDK",
		bucket: "hopermall",
		secure: true
	});
	let file = obj.file;
	//判断图片大小验证
	if (file.size) {
	}
	let fileName = getFileNameUUID();
	try {
		client
			.multipartUpload(fileName, file, {
				progress: percentage => {
					obj.onProgress(percentage);
				}
			})
			.then(res => {
				let url = res.res.requestUrls[0];
				if (url.indexOf("?") != -1) {
					url = url.substring(0, url.indexOf("?"));
				}
				let result = {
					name: res.name,
					status: "success",
					url: url,
					res: res
				};
				console.log("result", result);
				client.putACL(result.name, "public-read");
				obj.onSuccess(result);
				if (callback) {
					callback(result);
				}
			});

		// let result = await client.put(fileName, file);
		// console.log(3333, result);
		// client.putACL(result.name, "public-read");
		// result.status = "success";
		// obj.onSuccess(result);
		// if (callback) {
		// 	callback(result);
		// }
	} catch (e) {
		obj.onError(e);
		console.log(1111, e);
	}
};

export default uploadFile;
